package models

import (
	"fly/schema"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

type SysMenu struct {
	BaseModel
	Name        string `orm:"column(name);description(名称)"`
	Url         string `orm:"column(url);description(菜单URL)"`
	Permissions string `orm:"column(permissions);description(授权:多个用逗号分隔)"`
	Pid         int64  `orm:"column(pid);description(上级ID，一级菜单为0)"`
	MenuType    int    `orm:"column(menu_type);description(类型   0：菜单   1：按钮)"`
	Icon        string `orm:"column(icon);description(菜单图标)"`
	Sort        int    `orm:"column(sort);description(排序)"`
}

func init() {
	orm.RegisterModel(new(SysMenu))
}

// SearchField 定义模型的可搜索字段
func (*SysMenu) SearchField() []string {
	return []string{"name", "url", "pid"}
}

// WhereField 定义模型可作为条件的字段
func (*SysMenu) WhereField() []string {
	return []string{"id", "status", "name", "url", "pid"}
}

func (m *SysMenu) TableName() string {
	return "sys_menu"
}

// AddSysMenu insert a new SysMenu into database and returns
// last inserted Id on success.
func AddSysMenu(m *SysMenu, userId int64) (id int64, err error) {
	o := orm.NewOrm()
	m.Creator = userId
	m.Updater = userId
	id, err = o.Insert(m)
	return
}

// GetSysMenuById retrieves SysMenu by Id. Returns error if
// Id doesn't exist
func GetSysMenuById(id int64) (v *SysMenu, err error) {
	o := orm.NewOrm()
	v = &SysMenu{BaseModel: BaseModel{Id: id}}
	if err = o.QueryTable(new(SysMenu)).Filter("id", id).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdateSysMenuById updates SysMenu by Id and returns error if
// the record to be updated doesn't exist
func UpdateSysMenuById(m *SysMenu, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysMenu{BaseModel: BaseModel{Id: m.Id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		m.Updater = userId
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSysMenu deletes SysMenu by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSysMenu(id int64) (err error) {
	o := orm.NewOrm()
	v := SysMenu{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SysMenu{BaseModel: BaseModel{Id: id}}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// DestroySysMenu Destroy SysMenu by Id and returns error
func DestroySysMenu(id int64, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysMenu{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Status = schema.StatusDelete
		v.Updater = userId
		var num int64
		if num, err = o.Update(v, "updater", "status"); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}
